<template>
  <div class="webgl-content map"  >
    <div id="unityContainer" class="map" ></div>
<!--    <div class="footer">
      <div class="fullscreen" @click.prevent="fullscreen">全屏</div>
    </div>-->
  </div>
</template>

<script>

import Vue from 'vue'

export default {
  name: 'UnityWebGL',
  props: ['width', 'height'],
  data () {
    return {
      unityLoader: 'unity3d/Build/UnityLoader.js',
      unityJson: 'unity3d/Build/web.json',
      unityInstance: null,
      error: null
    }
  },
  destroyed () {
    // 资源回收
    console.log('unity资源回收')
  },
  beforeMount () {
    if (!this.eventBus) {
      this.eventBus = new Vue({
        data: {
          ready: false,
          load: false
        }
      })
    }

    if (typeof UnityLoader === 'undefined' && this.unityLoader && !this.eventBus.load) {
      const script = document.createElement('SCRIPT')
      script.setAttribute('src', this.unityLoader)
      script.setAttribute('async', '')
      script.setAttribute('defer', '')
      document.body.appendChild(script)
      this.eventBus.load = true
      script.onload = () => {
        this.eventBus.ready = true
        this.eventBus.$emit('onload')
      }
    } else {
      this.eventBus.ready = true
      this.eventBus.load = true
    }
  },
  mounted () {
    const instantiate = () => {
      if (typeof UnityLoader === 'undefined') {
        let error = 'The UnityLoader was not defined, please add the script tag ' +
                'to the base html and embed the UnityLoader.js file Unity exported or use "unityLoader" attribute for path to UnityLoader.js.'
        console.error(error)
        this.error = error
        return
      }
      if (this.src === null) {
        let error = 'Please provice a path to a valid JSON in the "src" attribute.'
        console.error(error)
        this.error = error
        return
      }
      let params = {}
      if (this.module) {
        params.Module = this.module
      }
      this.unityInstance = UnityLoader.instantiate('unityContainer', this.unityJson, params)
    }

    if (this.eventBus.ready) {
      instantiate()
    } else {
      this.eventBus.$on('onload', () => {
        instantiate()
      })
    }
  },
  methods: {
    fullscreen () {
      this.unityInstance.SetFullscreen(1)
    },
    message (gameObject, method, param) {
      if (param === null) {
        param = ''
      }
      if (this.unityInstance !== null) {
        this.unityInstance.SendMessage(gameObject, method, param)
      } else {
        console.warn('vue-unity-webgl: you\'ve sent a message to the Unity content, but it wasn\t instantiated yet.')
      }
    }
  }
}

</script>

<style scoped>
.fullscreen{
  text-align: right;
  color: #fffffe;
  font-size: 18px;
}
.map{
        height: calc(100vh - 110px);
    }
</style>
